<?php
/**
 * Created by PhpStorm.
 * User: ytlmi
 * Date: 2017/10/17
 * Time: 10:21
 */

namespace org\util\wordtool;


class Table
{
    protected $page = null;//所属的页面DOMDocument实例
    protected $tbl = null;//表格节点

    /**
     * @param \DOMNode $table
     * @param array $style
     * 构造函数
     */
    public function __construct(\DOMNode $table, $style = null)
    {
        $this->tbl = $table;
        $this->page = $this->tbl->ownerDocument;
        $this->addTblPr($style);
    }

    /**
     * @param array $style
     * @return Table
     * @throws \Exception
     * 加入表格样式节点
     */
    protected function addTblPr($style)
    {
        $objStyle = new Style();
        try{
            $tblPr = $objStyle->createTBLPR($style);
        }catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        $this->tbl->appendChild($this->page->importNode($tblPr, true));
        return $this;
    }

    /**
     * @param array $style
     * @return TableRow
     * 添加行
     */
    public function addRow($style = null)
    {
        return new TableRow($this->tbl,$style);
    }

    /**
     * @param array $arr_text
     * @param mixed $width
     * @param mixed $font
     * @param array $style
     * @return Table
     * @throws \Exception
     * 直接输入一行单元格
     * 文本为数组，宽度可设置单一的也可设置数组
     */
    public function addSimpleRow($arr_text,$width, $font, $style)
    {
        $tr = $this->addRow(isset($style['height']) ? $style['height'] : null);

        //验证宽度参数
        $arr_width=[];
        if (isset($width)){
            if(is_array($width)){
                $arr_width=$width;
            }elseif (is_int($width+0)){
                for ($i=0;$i<count($arr_text);$i++){
                    $arr_width[]=$width;
                }
            }else{
                for ($i=0;$i<count($arr_text);$i++){
                    $arr_width[]=500;
                }
            }
        }
        for ($i = 0; $i < count($arr_text); $i++) {
            $style['width'] = $arr_width[$i];
            $tr->addCell(null,$style)->addText($arr_text[$i],$font,$style);
        }
        return $this;
    }


}